var Ssn = new Object();

Ssn = {
	jsn_num : 3,
	jsn_cnt : 0
};

var prod, stores, cats, prodCnt, prodsLoaded, storesLoaded;
prodCnt = new Array();
prodsLoaded = storesLoaded = false;
var dbp = "../db/";

function getData() {
	$.getJSON(dbp + 'cats.json', function(data) {
		cats = data;
		cats = sortByKey(cats, 'nm');

		Ssn.jsn_cnt++;
	});

	$.getJSON(dbp + 'stores.json', function(data) {
		stores = data;
		stores = sortByKey(stores, 'nm');
		Ssn.jsn_cnt++;

	});

	$.getJSON(dbp + 'products.json', function(data) {
		prod = data;
		prod = sortByKey(prod, 'nm');
		$.each(prod, function(key, val) {
			if (prodCnt[val.vt])
				prodCnt[val.vt] += 1;
			else
				prodCnt[val.vt] = 1;
				
				
			if (prodCnt[val.ct])
				prodCnt[val.ct] += 1;
			else
				prodCnt[val.ct] = 1;	
		});
		Ssn.jsn_cnt++;
	});
}

function takeOff() {
	for ( var i = 0; i < stores.length; i++) {
		stores[i]._pc = cntRec(prod, 'vt', stores[i].id);
	}

	for ( var i = 0; i < cats.length; i++) {
		cats[i]._pc = cntRec(prod, 'ct', cats[i].id);
	}
	
	
	for ( var i = 0; i < stores.length; i++) {
		stores[i]._cc=[];
		for ( var j = 0; j < cats.length; j++) {
			stores[i]._cc[j]=cntRec(prod, "vt\1ct", stores[i].id+"\1"+cats[j].id); 
		}
	}
}

function cntRec(lst, prp, val) {
	var cnt = 0, mtp=false, prp_a=[], val_a=[];
	if (prp.indexOf('\1')>0) {
		mtp=true;
		prp_a=prp.split('\1');
		val_a=val.split('\1');
	}
	for ( var i = 0; i < lst.length; i++) {
		if (mtp) {
			var fnd=true;
			for (var j=0;fnd && j<prp_a.length;j++)
				fnd&=lst[i][prp_a[j]] === val_a[j];
			if (fnd)
				cnt++;
		}
		else if (lst[i][prp] === val)
			cnt++;
	}
	return cnt;
}

// function getRecRow(lst, prp, val, frm) {
// if (!frm)
// frm=0;
// for ( var i = frm; i < lst.length; i++) {
// if (lst[i][prp] === val)
// return i;
// }
// return -1;
// }

function continueExecution() {
	if (Ssn.jsn_cnt != Ssn.jsn_num) {
		console.log("start continueExecution in 100ms");
		setTimeout(continueExecution, 100);
	} else
		takeOff();
}

function addCnt(obj) {

}

function sortByKey(array, key) {
	return array.sort(function(a, b) {
		var x = a[key], y = b[key];
		return ((x < y) ? -1 : ((x > y) ? 1 : 0));
	});
}
